package com.linewell.system.interceptor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.linewell.commom.dao.impl.BaseDaoImpl;
import com.linewell.system.model.SysMenuActions;
import com.linewell.system.model.SysMenus;
import com.linewell.system.pagemodel.ReturnInfo;
import com.linewell.system.utils.JsonUtil;

/**
 * 登录拦截器
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BackendInterceptor extends BaseDaoImpl implements HandlerInterceptor {
	
	private static final Log log = LogFactory.getLog(BackendInterceptor.class);
	private List<String> excludeUrls; // 后台用户登录之后可以访问的地址和其他不需要拦截的地址
	private List<String> frontExcludeUrls; // 微信前端用户拦截地址
	private static List<String> menuActionUrls = new ArrayList<String>();// 需要验证的地址
	//其他类给menuActionUrls添加操作地址,使得添加完权限后直接生效,无需重新登录
	public static void addMenu(String url){
		menuActionUrls.add(url);
	}
	public List<String> getMenuActionUrls() {
		log.info("--------------------------------------------以下为获取权限地址-----------------------------------------------");
		// 从数据库查询出已配置可以访问的地址
		if(menuActionUrls.size() > 0){
			menuActionUrls.clear();
		}
		String hql = null;
		List<SysMenus> lst = null;
		try {
			hql = " from SysMenus t where t.type = 3 and t.status = 9 ";
			lst = super.find(hql);
		} catch (HibernateException e) {
			log.info("异常："+e.getMessage());
			e.printStackTrace();
		}
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < lst.size(); i++) {
			str.append(lst.get(i).getId() + ",");
		}
		String desstr = str.toString();
		desstr = desstr.substring(0, desstr.length() - 1);
		List<SysMenuActions> lst2 = null;
		try {
			hql = " from SysMenuActions t where t.menuId in (" + desstr + ") ";
			lst2 = super.find(hql);
		} catch (HibernateException e) {
			log.info("异常："+e.getMessage());
			e.printStackTrace();
		}
		Iterator<SysMenuActions> it = lst2.iterator();
		while (it.hasNext()) {
			SysMenuActions rd = it.next();
			String url = rd.getActionUrl();
			// int id = rd.getId();
			menuActionUrls.add(url);
		}
		log.info("--------------------------------------------权限地址获取完成-----------------------------------------------");
		return menuActionUrls;

	}

	public List<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}
	public List<String> getFrontExcludeUrls() {
		return frontExcludeUrls;
	}

	public void setFrontExcludeUrls(List<String> frontExcludeUrls) {
		this.frontExcludeUrls = frontExcludeUrls;
	}

	/**
	 * 在渲染视图后被调用，用于释放资源
	 * 
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	/**
	 * 在渲染视图前被调用
	 * 
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		
	}
	/**
	 * 在访问action前被调用
	 * 
	 */
	@Override
	@ResponseBody
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		/**
		 * 条件：
		 * 1.在spring-mvc配置文件中配置如登录等本身不需要权限验证的地址
		 *  2.从菜单表中查询出可以操作的地址
		 * 满足以上任一条件，则放行
		 */

		HttpSession session = request.getSession();
		Object obj = session.getAttribute("user");
		String curActionUrl = request.getServletPath();
		if (obj != null) { // 后台用户已登录
			if(menuActionUrls.size() == 0){		//保证权限获取只需一次
				menuActionUrls = getMenuActionUrls();
			}
			if (menuActionUrls.contains(curActionUrl) || excludeUrls.contains(curActionUrl) || frontExcludeUrls.contains(curActionUrl)) {// 表示用户允许的操作地址中包括当前地址
				return true;  //放行		
			} else {
				log.info("被拦截地址：" + request.getServletPath() + " 将该地址添加至系统对应菜单中——>Action中即可");
				response.setCharacterEncoding("utf-8");
				response.getWriter().print(JsonUtil.toJson(returnInfo()));
				return false;
			}
		} else{
				// 用户未登录，跳转至登录页
				response.sendRedirect("/manage");
				return false;
			}					
		
	}	
	@ResponseBody
	public ReturnInfo returnInfo() {
		ReturnInfo info = new ReturnInfo();
		info.setMsg("你没有操作该地址的权限！");
		info.setSuccess(1);
		return info;
	}
}
